using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OpenComposite.EII.Repository;
using System.Xml.Schema;
using System.Xml;
using OpenComposite.Mapper;
using System.Xml.Serialization;
using System.IO;
using OpenComposite.Base.Collections;

namespace OpenComposite.EII.Designer.Workflow
{
	public partial class FormLogicalCapabilityConfiguration : Form
	{
		#region Initialization
		public FormLogicalCapabilityConfiguration(Repository.Workflow workflow)
		{
			_workflow = workflow;

			InitializeComponent();

			init();
		}

		private void init()
		{
			//showOperation();
			this.tsbtnCancel.Visible = false;
		}

		#endregion

		#region Public Members

		#region Properties

		public Repository.Operation Operation
		{
			get { return _operation; }
		}
		public string InputConnections
		{
			get { return _inputConnections; }
		}
		public XsltDocument InputXSLT
		{
			get { return _inputXSLT; }
		}
		public string PhysicalInputConnections
		{
			get { return _inputConnectionsPhys; }
		}
		public XsltDocument PhysicalInputXSLT
		{
			get { return _inputXSLTPhys; }
		}
		//public string SelectedBObjectsString
		//{
		//    get
		//    {
		//        string s = "";
		//        foreach ( BusinessObject bo in lstDocumentSubscriptions.Items ) {
		//            if ( s != "" )
		//                s += cSeperator;
		//            s += bo.ID;
		//        }
		//        return s;
		//    }
		//}
		//public BusinessObject[] SelectedBObjects
		//{
		//    get
		//    {
		//        BusinessObject[] bobjects = new BusinessObject[lstDocumentSubscriptions.Items.Count];
		//        lstDocumentSubscriptions.Items.CopyTo(bobjects, 0);
		//        return bobjects;
		//    }
		//}

		#endregion

		#region Methods

		public void Init(string logactName, LogicalActivity logact/*, int operationId,
						 string inputConnections, string inputConnectionsPhysical,
						 List<BusinessObject> selectedBObjects*/
																)
		{
			RepositoryService repSvc = (RepositoryService)_workflow.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			txtLogActName.Text = logactName;
			_logact = logact;
			if ( _logact != null ) {
				txtOperation.Text = _logact.Name;

				BusinessObject bo = _logact.InputBusinessObject;
				txtInputSchema.Text = ( bo != null ? bo.Name : "" );

				bo = _logact.OutputBusinessObject;
				txtOutputSchema.Text = ( bo != null ? bo.Name : "" );
			} else {
				txtOperation.Text = "Please assign a Business Capability.";
				txtInputSchema.Text = "";
				txtOutputSchema.Text = "";
			}
			//if ( operationId > 0 ) {
			//    _operation = repSvc.GetItem(ItemType.Operation, operationId, true) as Repository.Operation;
			//    showOperation();
			//} else {
			//    _operation = null;
			//}
			//// set input connections
			//_inputConnections = inputConnections;
			//_inputConnectionsPhys = inputConnectionsPhysical;
			//// set subscribed business objects
			//lstDocumentSubscriptions.Items.Clear();
			//lstDocumentSubscriptions.Items.AddRange(selectedBObjects.ToArray());
		}

		#endregion

		#endregion

		#region Private Members

		#region Constants
		private const char cSeperator = ';';
		#endregion

		#region Variables
		private Repository.Workflow _workflow = null;
		private Repository.Operation _operation = null;
		private Repository.LogicalActivity _logact = null;

		private XsltDocument _inputXSLT = null;
		private string _inputConnections = null;

		private XsltDocument _inputXSLTPhys = null;
		private string _inputConnectionsPhys = null;

		#endregion

		#region Methods

		private void selectOperation()
		{
			BindingListEx<Operation> lstOps = Global.Data.GetWorkflowOperation(_workflow.ID);
			if ( lstOps != null && lstOps.Count > 0 ) {
				Service svc = lstOps[0].GetService();
				if ( svc != null ) {
					Forms.FormSelectReferencedOperation frm =
						new OpenComposite.EII.Designer.Workflow.Forms.FormSelectReferencedOperation(svc);
					if ( frm.ShowDialog() == DialogResult.OK ) {
						_operation = frm.SelectedOperation;
						showOperation();
					}
				}
			}
		}

		//private void selectBObject()
		//{
		//    OpenComposite.EII.Forms.FormSelectRepositoryEx frm = new OpenComposite.EII.Forms.FormSelectRepositoryEx(_workflow);
		//    frm.RepositoryID = Global.Status.CurrentRepositoryId;
		//    frm.DomainID = Global.Status.CurrentDomainId;
		//    frm.AllowedTypes = new ItemType[] { OpenComposite.EII.Repository.ItemType.BObject };
		//    frm.MultiSelect = true;
		//    List<RepositoryItemBase> lstSelected = new List<RepositoryItemBase>();
		//    foreach ( BusinessObject bobj in lstDocumentSubscriptions.Items ) {
		//        lstSelected.Add(bobj);
		//    }
		//    if ( lstSelected.Count > 0 )
		//        frm.SetSelectedItems(lstSelected);

		//    if ( frm.ShowDialog() == DialogResult.OK ) {
		//        //Repository.BusinessObject bo = frm.SelectedItem as Repository.BusinessObject;
		//        //if ( bo != null ) {
		//        //lstDocumentSubscriptions.Items.Clear();
		//        //lstDocumentSubscriptions.Items.AddRange(frm.GetSelectedItems().ToArray());
		//        //}
		//    }
		//}
		//private void removeBObjects()
		//{
		//    while ( lstDocumentSubscriptions.SelectedItems.Count > 0 ) {
		//        lstDocumentSubscriptions.Items.Remove(lstDocumentSubscriptions.SelectedItems[0]);
		//    }
		//}

		//private void setInputMapping()
		//{
		//    List<XmlSchema> schemas = new List<XmlSchema>();
		//    foreach ( Repository.BusinessObject bo in lstDocumentSubscriptions.Items ) {
		//        schemas.Add(bo.Schema);
		//    }

		//    XmlSchema xsdSubscriptions = createCompoundDocument(schemas);

		//    Mapper.FormMapping frm = new OpenComposite.Mapper.FormMapping();
		//    frm.InitializeMapper(xsdSubscriptions, _operation.InputSchema, _inputConnections);
		//    if ( frm.ShowDialog() == DialogResult.OK ) {
		//        _inputXSLT = frm.GetMapping(out _inputConnections);
		//    }
		//}
		//private void setInputMappingPhysical()
		//{
		//    List<XmlSchema> schemas = new List<XmlSchema>();
		//    foreach ( Repository.BusinessObject bo in lstDocumentSubscriptions.Items ) {
		//        schemas.Add(bo.Schema);
		//    }

		//    XmlSchema xsdSubscriptions = createCompoundDocument(schemas);

		//    Mapper.FormMapping frm = new OpenComposite.Mapper.FormMapping();
		//    List<Repository.WebMethod> lstWebMethods = Global.Data.GetOperationWebMethods(_operation.ID);
		//    if ( lstWebMethods.Count == 0 ) {
		//        MessageBox.Show("No Binding to WebMethod exists.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
		//        return;
		//    }
		//    frm.InitializeMapper(xsdSubscriptions, lstWebMethods[lstWebMethods.Count-1].InputSchema, _inputConnectionsPhys);
		//    if ( frm.ShowDialog() == DialogResult.OK ) {
		//        _inputXSLTPhys = frm.GetMapping(out _inputConnectionsPhys);
		//    }
		//}
		//private XmlSchema createCompoundDocument(List<XmlSchema> schemas)
		//{
		//    if ( schemas.Count == 0 ) {
		//        return null;
		//    }

		//    XmlSchemaSet xset = new XmlSchemaSet();

		//    //init Compound Schema
		//    XmlSchema compSchema = new XmlSchema();
		//    compSchema.ElementFormDefault = XmlSchemaForm.Qualified;
		//    compSchema.AttributeFormDefault = XmlSchemaForm.Qualified;
		//    compSchema.TargetNamespace = schemas[0].TargetNamespace;
		//    compSchema.Namespaces.Add("tns", "http://www.OpenComposite.com/canonical_document");
		//    compSchema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");

		//    //init choice-Element for adding Elements to the Schema
		//    XmlSchemaElement element = new XmlSchemaElement();
		//    element.Name = "SubscribedDocuments";
		//    XmlSchemaComplexType complexType = new XmlSchemaComplexType();
		//    element.SchemaType = complexType;
		//    XmlSchemaSequence seq = new XmlSchemaSequence();
		//    complexType.Particle = seq;

		//    int counter = 0;
		//    foreach ( XmlSchema schema in schemas ) {
		//        foreach ( XmlQualifiedName qname in schema.Namespaces.ToArray() ) {
		//            if ( qname.Namespace == "http://www.w3.org/2001/XMLSchema" ||
		//                 qname.Namespace == "http://www.OpenComposite.com/canonical_document" )
		//                continue;

		//            compSchema.Namespaces.Add(string.Format("compSch{0}", counter),
		//                qname.Namespace);
		//            counter++;
		//        }
		//        xset.Add(schema);
		//    }
		//    xset.Compile();
		//    if ( !xset.IsCompiled ) {
		//        throw new Exception("Compiling Schemas failed in FormLogicalActivityConfiguration.createCompoundDocument(..).");
		//    }
		//    for ( int i = 0; i < schemas.Count; i++ ) {
		//        foreach ( XmlSchemaObject schemaObj in schemas[i].Items ) {
		//            if ( schemaObj is XmlSchemaElement ) {
		//                bool exists = false;
		//                foreach ( XmlSchemaObject xmlObj in seq.Items ) {
		//                    if ( xmlObj is XmlSchemaElement ) {
		//                        if ( ( (XmlSchemaElement)xmlObj ).QualifiedName ==
		//                            ( (XmlSchemaElement)schemaObj ).QualifiedName ) {
		//                            exists = true;
		//                        }
		//                    }
		//                }
		//                if ( exists == false ) {
		//                    seq.Items.Add(schemaObj);
		//                }
		//            } else {
		//                if ( compSchema.Items.Contains(schemaObj) == false ) {
		//                    compSchema.Items.Add(schemaObj);
		//                }
		//            }
		//        }
		//    }


		//    //add compound Element that contains the subscribed Elements
		//    if ( compSchema.Items.Contains(element) == false ) {
		//        compSchema.Items.Add(element);
		//    }

		//    xset = new XmlSchemaSet();
		//    xset.Add(compSchema);
		//    //xset.ValidationEventHandler += new ValidationEventHandler(this.validationEventHandler);
		//    xset.Compile();

		//    return compSchema;
		//}

		private void showOperation()
		{
			if ( _operation != null ) {
				txtOperation.Text = _operation.Name;

				BusinessObject bo = _operation.GetInputBusinessObject();
				txtInputSchema.Text = ( bo != null ? bo.Name : "" );

				bo = _operation.GetOutputBusinessObject();
				txtOutputSchema.Text = ( bo != null ? bo.Name : "" );
			} else {
				txtOperation.Text = "Please select an operation.";
				txtInputSchema.Text = "";
				txtOutputSchema.Text = "";
			}
		}
		//private void showOperation()
		//{
		//    if ( _operation != null ) {
		//        txtComposite.Text = _operation.Name;
		//        txtInputSchema.Text = _operation.InputSchemaString;
		//        txtOutputSchema.Text = _operation.OutputSchemaString;
		//    } else {
		//        txtComposite.Text = "Please select an composite.";
		//        txtInputSchema.Text = "";
		//        txtOutputSchema.Text = "";
		//    }
		//}
		private void showSchema(string sSchema)
		{
			if ( string.IsNullOrEmpty(sSchema) )
				return;

			XmlDocument xd = new XmlDocument();
			xd.LoadXml(sSchema);

			formXmlViewer frm = new formXmlViewer();
			frm.XmlDocument = xd;
			frm.ShowDialog();
		}

		#endregion

		#region Event Handler

		private void btnSelectOperation_Click(object sender, EventArgs e)
		{
			selectOperation();
		}

		private void btnViewInputSchema_Click(object sender, EventArgs e)
		{
			//if ( _operation != null )
			//    showSchema(_operation.InputSchemaString);
			if ( _logact != null && _logact.InputBusinessObject != null )
				showSchema(_logact.InputBusinessObject.SchemaString);
		}

		private void btnViewOutputSchema_Click(object sender, EventArgs e)
		{
			//if ( _operation != null )
			//    showSchema(_operation.OutputSchemaString);
			if ( _logact != null && _logact.OutputBusinessObject != null )
				showSchema(_logact.OutputBusinessObject.SchemaString);
		}

		//private void btnAddDocument_Click(object sender, EventArgs e)
		//{
		//    selectBObject();
		//}

		//private void btnRemoveDocument_Click(object sender, EventArgs e)
		//{
		//    removeBObjects();
		//}

		//private void btnDefineInputMapping_Click(object sender, EventArgs e)
		//{
		//    setInputMapping();
		//}
		//private void btnDefinePhysMapping_Click(object sender, EventArgs e)
		//{
		//    setInputMappingPhysical();
		//}

		private void tsbtnOK_Click(object sender, EventArgs e)
		{
			//if ( _operation == null ) {
			//    MessageBox.Show("Please select an Operation.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
			//    btnSelectOperation.Focus();
			//    return;
			//}
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}
		private void tsbtnCancel_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

		#endregion

		#endregion

	}
}